package com.xy.common.util;


import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.lang.NonNull;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

/**
 * @author xiao.yi
 * @date 2023/9/28 14:24
 */
@Slf4j
public class WebHelper {
    public static String encodeDownloadFileName(HttpServletRequest request, @NonNull String fileName) {
        try {
            String encodedFileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8.name()).replaceAll("\\+", "%20");
            UserDevice ud = UserAgent.getUserDevice(request);
            String defaultDownloadFilename = "filename=\"" + encodedFileName + "\"; filename*=UTF-8''" + encodedFileName;
            if (StrUtil.isBlank(ud.getUa())) {
                return defaultDownloadFilename;
            } else if ("edge".equals(ud.getBrowser())) {
                log.debug("Edge");
                return defaultDownloadFilename;
            } else {
                String iso8859Filename = "filename=\"" + new String(fileName.replaceAll(" ", "").getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1) + "\"";
                if ("firefox".equals(ud.getBrowser())) {
                    log.debug("Firefox");
                    return "filename=\"" + URLEncoder.encode(fileName, StandardCharsets.UTF_8.toString()) + "\"";
                } else if ("ie".equals(ud.getBrowser())) {
                    log.debug("IE");
                    return defaultDownloadFilename;
                } else if ("android".equals(ud.getDeviceType())) {
                    log.debug("android");
                    return iso8859Filename;
                } else if ("safari".equals(ud.getBrowser())) {
                    log.debug("Safari");
                    return iso8859Filename;
                } else if ("chrome".equals(ud.getBrowser())) {
                    log.debug("Chrome");
                    return defaultDownloadFilename;
                } else if ("crios".equals(ud.getBrowser())) {
                    log.debug("crios");
                    return defaultDownloadFilename;
                } else {
                    log.debug("Others");
                    return defaultDownloadFilename;
                }
            }
        } catch (UnsupportedEncodingException var6) {
            throw new RuntimeException(var6);
        }
    }

    public static String getContentDisposition(HttpServletRequest request, String filename) {
        return "attachment; " + encodeDownloadFileName(request, filename);
    }
}
